package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.client.cmn.DictFeignClient;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.BookingRule;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    //把获取map集合数据添加mongodb
    @Override
    public void saveHosp(Map<String, Object> paramMapString) {
        //paramMapString -- Hospital
        // gson jackson fastjson
        //1 paramMapString转换json字符串
        String jsonString = JSONObject.toJSONString(paramMapString);
        //2 把转换json字符串变成对象
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        // 根据医院编号查询
        String hoscode = hospital.getHoscode();
        Hospital existHospital = hospitalRepository.findHospByHoscode(hoscode);
        ////判断：mongodb是否存在相同医院，如果存在更新，不存在添加
        if(existHospital != null) { //存在相同医院，更新
            //设置id值
            hospital.setId(existHospital.getId());
            //修改时间
            hospital.setUpdateTime(new Date());
            //添加时间
            hospital.setCreateTime(existHospital.getCreateTime());
            hospital.setStatus(0);
            //save方法参数是Hospital带值对象
            hospitalRepository.save(hospital);
        } else { //不存在，添加
            //修改时间
            hospital.setUpdateTime(new Date());
            //添加时间
            hospital.setCreateTime(new Date());
            hospital.setStatus(0);
            //save方法参数是Hospital带值对象
            hospitalRepository.save(hospital);
        }

    }

    //获取医院信息
    @Override
    public Hospital findHospHoscode(String hoscode) {
        return hospitalRepository.findHospByHoscode(hoscode);
    }

    //医院列表（条件查询分页）
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit,
                                         HospitalQueryVo hospitalQueryVo) {
        //设置排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        //设置分页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        //封装条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);

        Example<Hospital> example = Example.of(hospital,matcher);

        //调用方法
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        //从分页查询page对象获取集合，
        // 集合遍历，
        // 得到每个医院对象，获取编号，
        // 根据编号远程调用得到名称，完成封装
//        List<Hospital> list = pages.getContent();
//        for(Hospital hosp : list) {
//
//        }
        pages.getContent().stream().forEach(item -> {
            this.packHospital(item);
        });

        return pages;
    }

    //更新上线状态
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            //根据id查询
            Hospital hospital = hospitalRepository.findById(id).get();
            //设置更新状态值
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            //调用方法更新
            hospitalRepository.save(hospital);
        }
    }

    //"获取医院详情"
    @Override
    public Map<String, Object> showDetail(String id) {
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        //获取预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        Map<String, Object> result = new HashMap<>();
        result.put("hospital",hospital);
        result.put("bookingRule", bookingRule);
        return result;
    }

    //获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital =  hospitalRepository.findHospByHoscode(hoscode);
        if(null != hospital){
            return hospital.getHosname();
        }
        return "";
    }

    //条件查询医院列表
    @Override
    public List<Hospital> selectHospQuery(HospitalQueryVo hospitalQueryVo) {
        //设置排序
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");

        //封装条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        Example<Hospital> example = Example.of(hospital, matcher);

        List<Hospital> list = hospitalRepository.findAll(example,sort);
        list.stream().forEach(item ->{
            this.packHospital(item);
        });
        return list;
    }

    //根据医院名称获取医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    //医院预约详情
    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String,Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(this.findHospHoscode(hoscode));
        result.put("hospital",hospital);
        //预约规则
        result.put("bookingRule",hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    //获取每个Hospital对象编号，把编号对应名称获取到，完成封装
    private Hospital packHospital(Hospital hospital) {
        //1 获取所有编号
        String hostype = hospital.getHostype(); //医院等级
        String provinceCode = hospital.getProvinceCode(); //省
        String cityCode = hospital.getCityCode(); //市
        String districtCode = hospital.getDistrictCode(); //区

        //2 远程调用获取编号对应名称
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hostype);
        String provinceString = dictFeignClient.getName(provinceCode);
        String cityString = dictFeignClient.getName(cityCode);
        String districtString = dictFeignClient.getName(districtCode);

        //3 封装
        hospital.getParam().put("hostypeString",hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }

}
